import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
import libman from "../libman.json";

const amis = libman.libraries.find(lib => lib.library.includes("amis")).library;
const loaders = {};

const AmisViewer = forwardRef(({ schema = {}, props = {}, env = {} }, ref) => {
  const refContainer = useRef(null);
  const [amisScoped, setAmisScoped] = useState();
  if (!loaders.amis) loaders.amis = window.MP.load([
    amis + '/sdk/antd.css',
    amis + '/sdk/helper.css',
    amis + '/sdk/iconfont.css',
    amis + '/sdk/sdk.js',
  ]);
  useImperativeHandle(ref, amisScoped);

  useEffect(() => {
    loaders.amis.then(() => {
      const amis = window.amisRequire('amis/embed');
      setAmisScoped(amis.embed(refContainer.current, {
        "type": "page",
        "title": "空白页面",
        ...schema,
      }, props, {
        theme: 'antd',
        ...env,
      }));
    });
    // eslint-disable-next-line
  }, []);

  return <div ref={refContainer} />;
});

export default AmisViewer;